<template>
  <div class="relation-ship">
    <div style="height: 200px">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2 :columns="columns" :data="tableModule.tableData" :width="width" :height="height"
            header-class="header-style" :header-height="40" :row-height="40" />
        </template>
      </el-auto-resizer>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import * as FormApi from '@/api/knowledge/character'
import { ref } from 'vue'
import { ElInput, ElSelect } from 'element-plus'
import type { FunctionalComponent } from 'vue'
import type { Column, InputInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const props = defineProps({
  dialogTitle: String
})
// 初始表格数据
var initialTableData = []
// 当前行数据
const currentRowData = ref({})
const open = async (data, entityRelationshipData) => {
  console.log(data)
  currentRowData.value = data
  initialTableData = entityRelationshipData
  console.log('initialTableData', initialTableData)
  Object.assign(tableModule.tableData, entityRelationshipData)
  tableModule.tableData.forEach((item) => {
    Object.assign(item, { graphName: data.rowData.graphName })
    Object.assign(item, { graphId: data.rowData.graphId })
  })
  console.log(tableModule.tableData)
}
defineExpose({ open })
// 表格数据
const tableModule = reactive({
  tableData: [
    { name: 'asdf', relationship: '前置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '前置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '前置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '前置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '前置' },
    { name: 'asdf', relationship: '后置' },
    { name: 'asdf', relationship: '后置' },
  ], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})
// 节点关系数据
const nodeRelationshipData = [
  {
    value: '前置',
    label: '前置',
  },
  {
    value: '后置',
    label: '后置',
  },
]
type SelectionCellProps = {
  value: string
  selectValue: string
  intermediate?: boolean
  onChange: (value: string) => void
  forwardRef: (el: InputInstance) => void
}
const InputCell: FunctionalComponent<SelectionCellProps> = ({ value, onChange, forwardRef }) => {
  return <ElInput ref={forwardRef as any} onInput={onChange} modelValue={value} />
}
const SelectCell: FunctionalComponent<SelectionCellProps> = ({ selectValue }) => {
  return (
    h(
      ElSelect,
      {
        modelValue: selectValue,
        'onUpdate:modelValue': (value: any, index: number) => {
          console.log('=log=onUpdate:modelValue=', value, index)
          selectValue = value
        },
        placeholder: '请选择节点关系',
        // clearable: true,
        style: 'width: 100%; padding: 20px 0px;',
        onChange: (value) => {
          console.log('onChange', value, selectValue)
        }
      },
      () => {
        const optionDom = []
        nodeRelationshipData.forEach((row) => {
          optionDom.push(h(ElOption, { label: row.label, value: row.value, disabled: false }))
        })
        return optionDom
      }
    )
  )
}
// 弹窗取消
const Cancel = () => {
  dialogTableVisible.value = false
}
// 弹窗确定
const submitForm = async () => {
  console.log('initialTableData', initialTableData)
  console.log(tableModule.tableData)
  const params = []
  tableModule.tableData.forEach((item) => {
    const paramsValue = {}
    Object.assign(paramsValue, { graphName: item.graphName }) // 所属图谱
    Object.assign(paramsValue, { graphId: item.graphId }) // 所属图谱ID
    Object.assign(paramsValue, { featureCode: item.endEntityId }) // 终止节点ID
    Object.assign(paramsValue, { newFeature: item.endEntity }) // 终止节点名称
    Object.assign(paramsValue, { newRelation: item.relation }) // 节点关系
    Object.assign(paramsValue, { entityCode: item.startEntityId }) // 起始节点ID
    params.push(paramsValue)
  })
  FormApi.updateRelationAndFeatureByCode(params).then((res) => {
    if (res.data === 0) return
    ElMessage({
      message: '修改成功',
      grouping: true,
      showClose: true,
      type: 'success'
    })
    dialogTableVisible.value = false
  })
}
// 发布
const handleRelease = (data: any, type: boolean) => {
  console.log('发布')
  console.log(data.rowData.id)
  const params = {
    featureCode: currentRowData.value.rowData.id,
    graphName: route.query.graphName,
    featureReleaseStatus: 0, // 0取消发布 1发布
  }
  if (type) params.featureReleaseStatus = 1
  else params.featureReleaseStatus = 0
  FormApi.updateFeatureReleaseStatusByFeatureCode(params).then(res => getTableData())
}
const getTableData = () => {
  console.log(currentRowData.value.rowData)
  const params = {
    entity: currentRowData.value.rowData.entityName,
    graphName: route.query.graphName
  }
  FormApi.findNeo4jByEntity(params).then((res) => {
    Object.assign(tableModule.tableData, res)
    tableModule.tableData.forEach((item) => {
      Object.assign(item, { graphName: currentRowData.value.rowData.graphName })
      Object.assign(item, { graphId: currentRowData.value.rowData.graphId })
    })
  })
}
// 删除
const deleteFcn = (data: any) => {
  ElMessageBox.confirm('确定永久删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(data.rowData.id)
      if (activeName.value === '2') {
        FormApi.deleteHybaseGraphEvent(data.rowData.id)
          .then((res: any) => {
            if (res.data === 0) return
            ElMessage({
              type: 'success',
              grouping: true,
              showClose: true,
              message: '删除已完成'
            })
            getTableData(activeName.value)
          })
          .catch((error: any) => {
            ElMessage({
              message: error,
              grouping: true,
              showClose: true,
              type: 'error'
            })
          })
      } else {
        FormApi.deleteHybaseGraphEntity(data.rowData.id)
          .then((res: any) => {
            if (res.data === 0) return
            ElMessage({
              type: 'success',
              grouping: true,
              showClose: true,
              message: '删除已完成'
            })
            getTableData(activeName.value)
          })
          .catch((error: any) => {
            ElMessage({
              message: error,
              grouping: true,
              showClose: true,
              type: 'error'
            })
          })
      }

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        grouping: true,
        showClose: true,
        message: '删除已取消'
      })
    })
}
//
const columns: Column<object>[] = [
  {
    key: 'name',
    title: '知识点名称',
    dataKey: 'name',
    width: 300,
    align: 'center',
    border: true,
    cellRenderer: ({ cellData: name }) => <div>{name}</div>
  },
  {
    key: 'relationship',
    title: '关系',
    dataKey: 'relationship',
    width: 300,
    align: 'center',
    cellRenderer: ({ rowData, column }) => {
      const onChange = (value: string) => {
        rowData[column.dataKey!] = value
      }
      const onEnterEditMode = () => {
        console.log(rowData)
        // editing为唯一属性，如多个列需要编辑时，需要使用新的属性名（editing2）
        rowData.editing = true
      }
      const onExitEditMode = () => (rowData.editing = false)
      const input = ref()
      const setRef = (el) => {
        input.value = el
        if (el) {
          el.focus?.()
        }
      }
      return rowData.editing ? (
        <SelectCell
          forwardRef={setRef}
          selectValue={rowData[column.dataKey!]}
          onChange={onChange}
          onBlur={onExitEditMode}
          onKeydownEnter={onExitEditMode}
        />
      ) : (
        <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
          {rowData[column.dataKey!]}
        </div>
      )
    }
  },
  {
    key: '操作',
    title: '操作',
    cellRenderer: (data) => (
      <>
        <el-button onClick={deleteFcn.bind(this, data)} type="danger" size="small">
          删除
        </el-button>
      </>
    ),
    width: 150,
    align: 'center'
  }
]
</script>
<style lang="scss" scoped>
::v-deep(.el-table-v2__header-wrapper) {
  background-color: #e8e8e8;

  .el-table-v2__header-cell {
    background-color: #e8e8e8;
  }
}

::v-deep(.el-table-v2__row) {
  border-right: 1px solid #ebeef5;

  .el-table-v2__row-cell {
    border-left: 1px solid #ebeef5;
  }
}

.relation-ship {}
</style>
